import sys
import os
import imp
import signal
import readline
import re
import logging

# FIXME: dirty, the only way I found to keep 1 reference between
# modules, useful for config module reloading
conf = []

def load_or_create_conf(reload=False):
    if reload:
        print "reloading"
        conf.remove(conf[0])
    else:
        if conf != []:
            return conf
    CONF_FILENAME = os.path.expanduser("~/.jablit_conf.py")
    try:
        conf.append(imp.load_source("conf", CONF_FILENAME))

    except IOError:
        open(CONF_FILENAME,'w').write("""jid = "romeo@montague.net/jablit..."
password = "juliet"
server = "talk.google.com"
port = 5223
aliases = {"juliet@gmail.com": "juju"}
""")
        print 'Config file created: %s, edit it and run jablit' % CONF_FILENAME
        sys.exit(0)

    # FIXME: dirty
    try:
        conf[0].aliases
    except AttributeError:
        logging.info("aliases not configured")
        conf[0].aliases = {}
    # FIXME: dirty
    try:
        conf[0].auto_messages
    except AttributeError:
        logging.info("auto_messages not configured")
        conf[0].auto_messages = {}
    # FIXME: dirty
    try:
        conf[0].prompt
    except AttributeError:
        conf[0].prompt = "> "

    # Compile regexps
    for jid_re in conf[0].auto_messages:
        jid_re[0] = re.compile(jid_re[0])
        tmp = {}
        for incoming_msg_re in jid_re[1].keys():
            tmp[re.compile(incoming_msg_re)] = jid_re[1][incoming_msg_re]
        jid_re[1] = tmp
    return conf

def sigint_handler(signum, frame):
    readline.redisplay()

# Control-C
def bind_signals():
    signal.signal(signal.SIGINT, sigint_handler)

